//
//  PhotographerView.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 10/2/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "PhotographerView.h"

#import "DayCell.h"
#import "FreeTimeCell.h"

@implementation PhotographerView
{
    DayCell * percell;
    DayCell * befcell;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self makeViews];
        self.hidden = YES;
    }
    return self;
}

-(void)makeViews
{
    self.dayArray = [[NSMutableArray alloc] init];
    self.dayArray1 = [[NSMutableArray alloc] init];
    self.dayArray2 = [[NSMutableArray alloc] init];
    self.statusArray = [[NSMutableArray alloc] init];
    
    self.bgView = [[UIView alloc] initWithFrame:self.bounds];
    _bgView.backgroundColor = [UIColor blackColor];
    _bgView.alpha = 0.3;
    
    [self addSubview:_bgView];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgViewClick)];
    [_bgView addGestureRecognizer:tap];
    
    
    UIView * view = [UIView initViewRect:CGRectMake(0, self.bounds.size.height-413.5, UI_SCREEN_WIDTH, 413.5) andBackGroudColor:[UIColor whiteColor]];
    [self addSubview:view];
    
    //三部分 -- 部分一
    monthLB = [UILabel initLabelText:@"" andRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 45) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:17] andTextColor:UIColorFromRGB(0x453d35) andTextAlignment:NSTextAlignmentCenter];
    [view addSubview:monthLB];
    
    monthButton = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-84, 0, 84, 45) btnImage:nil btnTitle:@"下一月"];
    [monthButton setTitle:@"上一月" forState:UIControlStateSelected];
    monthButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [monthButton setTitleColor:UIColorFromRGB(0xffb619) forState:UIControlStateNormal];
    [monthButton addTarget:self action:@selector(monthButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:monthButton];
    
    NSArray * weekArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    for (int i = 0; i <7;i++){
        UILabel * lb = [UILabel initLabelText:[weekArray objectAtIndex:i] andRect:CGRectMake(6+44*i, 3+height_y(monthLB), 44, 32) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:14] andTextColor:UIColorFromRGB(0x453d35) andTextAlignment:NSTextAlignmentCenter];
        if (i == 0||i==6){
            lb.textColor = UIColorFromRGB(0xb6b6b6);
        }
        [view addSubview:lb];
    }
    
    //--部分二
    [self initDayCollectionViews:3+height_y(monthLB)+32 view:view];
    
    //--部分三
    [self initStatusCollenctionViews:view];
    
    [self getDayDatas];
}

-(void)initDayCollectionViews:(CGFloat)height view:(UIView *)view
{
    UICollectionViewFlowLayout * dayflowLayout = [[UICollectionViewFlowLayout alloc] init];
    dayflowLayout.minimumInteritemSpacing =0;
    dayflowLayout.minimumLineSpacing =0;
    [dayflowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    dayCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(6,height, UI_SCREEN_WIDTH-12, 365/2.0f) collectionViewLayout:dayflowLayout];
    [dayCollectionView registerClass:[DayCell class] forCellWithReuseIdentifier:@"dayCell"];
    dayCollectionView.backgroundColor = [UIColor clearColor];
    dayCollectionView.bounces = NO;
    dayCollectionView.alwaysBounceVertical = YES;
    dayCollectionView.delegate = self;
    dayCollectionView.dataSource = self;
    [view addSubview:dayCollectionView];
}

-(void)initStatusCollenctionViews:(UIView *)view
{
    UICollectionViewFlowLayout * statusflowLayout = [[UICollectionViewFlowLayout alloc] init];
    statusflowLayout.minimumInteritemSpacing =0;
    statusflowLayout.minimumLineSpacing =1;
    [statusflowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    stausCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(6,height_y(dayCollectionView), UI_SCREEN_WIDTH-11, 137) collectionViewLayout:statusflowLayout];
    [stausCollectionView registerClass:[FreeTimeCell class] forCellWithReuseIdentifier:@"statusCell"];
    stausCollectionView.backgroundColor = UIColorFromRGB(0xd4ccc5);
    stausCollectionView.bounces = NO;
    stausCollectionView.alwaysBounceVertical = YES;
    stausCollectionView.delegate = self;
    stausCollectionView.dataSource = self;
    [view addSubview:stausCollectionView];
}

-(void)monthButtonClick
{
    DDLOG_CURRENT_METHOD;
    monthButton.selected = !monthButton.selected;
    if (monthButton.isSelected){
        _dayArray = _dayArray2;
    }else{
        _dayArray = _dayArray1;
    }
    [_statusArray removeAllObjects];
    [dayCollectionView reloadData];
    [stausCollectionView reloadData];
}

-(void)bgViewClick
{
    [self hiddenThePhotographerView];
}

-(void)hiddenThePhotographerView
{
    self.hidden = YES;
}

-(void)showThePHotographerView
{
    self.hidden = NO;
}

#pragma mark
#pragma mark UICollcitonView Delegate
//设置分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个分区上的元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == dayCollectionView){
        return [_dayArray count];
    }
    return 12;
}

//设置元素内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == stausCollectionView){
        
        static NSString * identify = @"statusCell";
        FreeTimeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        
        cell.bgView.backgroundColor = UIColorFromRGB(0xe6e6e6);
        cell.hourLB.textColor = UIColorFromRGB(0x999999);
        cell.statusLB.textColor = UIColorFromRGB(0x999999);
        cell.hourLB.text = [NSString stringWithFormat:@"%d点",indexPath.row+8];
        if (ARRAY_IS_NOT_EMPTY(_statusArray)){
            for (int i =[_statusArray count]-1;i>=0;i--){
                if (indexPath.row +8 == [[_statusArray objectAtIndex:i][@"number"] intValue]){
                    cell.statusLB.text = [_statusArray objectAtIndex:i][@"status"];
                    if([cell.statusLB.text isEqualToString:@"空闲"]){
                        cell.bgView.backgroundColor = UIColorFromRGB(0xffffff);
                        cell.hourLB.textColor = UIColorFromRGB(0x453d35);
                        cell.statusLB.textColor = UIColorFromRGB(0xa2d339);
                    }else{
                        cell.bgView.backgroundColor = UIColorFromRGB(0xe6e6e6);
                        cell.hourLB.textColor = UIColorFromRGB(0x999999);
                        cell.statusLB.textColor = UIColorFromRGB(0x999999);
                        break;                    
                    }
                }
            }
        }else{
            cell.statusLB.text = nil;
        }
        return cell;
    }
    static NSString * identify = @"dayCell";
    DayCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
    cell.contentLB.backgroundColor = [UIColor whiteColor];
    cell.contentLB.enabled =YES;
    cell.contentLB.textColor = UIColorFromRGB(0x453d35);
    
    if ([[_dayArray objectAtIndex:indexPath.row] isKindOfClass:[NSString class]]){
        cell.contentLB.text =@"";
        cell.contentLB.enabled = NO;
        return cell;
    }
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents * comps;
    comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:[_dayArray objectAtIndex:indexPath.row]];
    monthLB.text = [NSString stringWithFormat:@"%d-%d",[comps year],[comps month]];
    if ([comps month]==[startComps month]){
        if ([lastComps month]!=[startComps month]){
            if ([comps day]>=[startComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
//                if ([comps weekday]==1||[comps weekday]==7){
//                    cell.contentLB.textColor = [UIColor lightGrayColor];
//                    cell.contentLB.enabled = NO;
//
//                }
            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;

            }
        }else{
            if ([comps day]>=[startComps day]&&[comps day]<=[startComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
//                if ([comps weekday]==1||[comps weekday]==7){
//                    cell.contentLB.textColor = [UIColor lightGrayColor];
//                    cell.contentLB.enabled = NO;
//
//                }
            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;

            }
        }
    }
    else if ([comps month] == [lastComps month]){
        if ([lastComps month]!=[startComps month]){
            if ([comps day]<=[lastComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
//                if ([comps weekday]==1||[comps weekday]==7){
//                    cell.contentLB.textColor = [UIColor lightGrayColor];
//                    cell.contentLB.enabled = NO;
//
//                }
            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;
            }
        }else{
            if ([comps day]>=[startComps day]&&[comps day]<=[startComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
//                if ([comps weekday]==1||[comps weekday]==7){
//                    cell.contentLB.textColor = [UIColor lightGrayColor];
//                    cell.contentLB.enabled = NO;
//                }
            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;
            }
        }
    }
    cell.contentLB.text = [NSString stringWithFormat:@"%d",[comps day]];
    return cell;
}

//设置元素的的大小框
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets top ={0,0,0,0};
    return top;
}

//设置顶部的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={0,0};
    return size;
}

//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(collectionView == dayCollectionView){
        return CGSizeMake(44,30.4);
    }
    return CGSizeMake(76, 45);
}

//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == stausCollectionView){
        return;
    }
    DayCell * cell  = (DayCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
    if(cell.contentLB.isEnabled){
       
        befcell.contentLB.backgroundColor = [UIColor whiteColor];
        befcell.contentLB.textColor = UIColorFromRGB(0x453d35);

        percell = cell;
        percell.contentLB.backgroundColor = UIColorFromRGB(0xffb619);
        percell.contentLB.textColor = [UIColor whiteColor];
    
        [_statusArray removeAllObjects];
        NSDate * date = [_dayArray objectAtIndex:indexPath.row];
        NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
        [dateFormat setDateFormat:@"yyyy-MM-dd"];
        NSString *  dateString = [dateFormat stringFromDate:date];
        for (NSDictionary * dict in _busyTimeArray){
            if ([dateString isEqualToString:dict[@"ShootDate"]]){
             //DateE结束时间  DateS 开始时间
                int startHour = [[[dict[@"DateS"] componentsSeparatedByString:@":"] firstObject] intValue];
                int  endHour = [[[dict[@"DateE"] componentsSeparatedByString:@":"] firstObject] intValue];
                for (int i = 8;i<=19;i++){
                    if (i>=startHour&&i<endHour){
                        NSDictionary * dict = @{@"number":[NSString stringWithFormat:@"%d",i],
                                                @"status":@"被预约"};
                        [_statusArray addObject:dict];
                    }else{
                        NSDictionary * dict = @{@"number":[NSString stringWithFormat:@"%d",i],
                                                @"status":@"空闲"};
                        [_statusArray addObject:dict];
                    }
                }
            }
        
        }
        if([_statusArray count]==0){
            for (int i =0;i<=19;i++){
                NSDictionary * dict = @{@"number":[NSString stringWithFormat:@"%d",i],
                                        @"status":@"空闲"};
                [_statusArray addObject:dict];
            }
        }
        
        [stausCollectionView reloadData];
        
        befcell = percell;
        
    }else{
        DDLOG(@"row = %d",indexPath.row);
    }
}

-(void)getDayDatas
{
    NSMutableArray * timeAarry = [[NSMutableArray alloc] init];
    
    NSDate * now = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents * comps;
    comps = [calendar components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
    
    int tmp = [comps day];
    for (int i =tmp-1;i>=0;i--){
        [comps setDay:-i];
        [comps setHour:0];
        [comps setMinute:0];
        [comps setSecond:0];
        
        NSDate * nowDate = [calendar dateByAddingComponents:comps toDate:now options:0];
        [timeAarry addObject:nowDate];

    }
    
    for (int i =1;i <=33;i++){
        [comps setDay:+i];
        [comps setHour:0];
        [comps setMinute:0];
        [comps setSecond:0];
        NSDate * nowDate = [calendar dateByAddingComponents:comps toDate:now options:0];
        
        [timeAarry addObject:nowDate];
        if (i == 3){
            startDate = nowDate;
        }
        if (i == 33){
            lastDate = nowDate;
        }
    }
    
    
    NSCalendar *lcalendar = [NSCalendar currentCalendar];
    NSDateComponents *lcomps;
    lcomps = [lcalendar components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[timeAarry lastObject]];
    
    NSDate * ldate = [timeAarry lastObject];
    
    NSDateComponents * tcomps;
    tcomps = [lcalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[timeAarry lastObject]];
    
    int a = [self countOfDayInYear:[tcomps year] month:[tcomps month]];
    
    for (int i = 1;i<=a-[tcomps day];i++){
        [lcomps setDay:+i];
        [lcomps setHour:0];
        [lcomps setMinute:0];
        [lcomps setSecond:0];
        NSDate * nowDate = [lcalendar dateByAddingComponents:lcomps toDate:ldate options:0];
        [timeAarry addObject:nowDate];
    }
    
    [_dayArray1 removeAllObjects];
    [_dayArray2 removeAllObjects];
//    [_dayArray addObjectsFromArray:timeAarry];
    
    startComps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:startDate];
    lastComps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:lastDate];
    
    
    comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
    for (int i = 0;i<[timeAarry count];i++){
        NSCalendar *dcalendar = [NSCalendar currentCalendar];
        NSDateComponents *dcomps;
        dcomps = [dcalendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[timeAarry objectAtIndex:i]];
        
        if ([dcomps year]==[comps year]&& [dcomps month]==[comps month]){
            [_dayArray1 addObject:[timeAarry objectAtIndex:i]];
        }
        if ([dcomps year] == [lastComps year]&&[dcomps month]==[lastComps month]){
            [_dayArray2 addObject:[timeAarry objectAtIndex:i]];
        }
    }

    comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:[timeAarry firstObject]];
    
    for (int i=1;i<[comps weekday];i++){
        [_dayArray1 insertObject:@"" atIndex:0];
    }
    
    comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:[timeAarry objectAtIndex:[timeAarry count]-a]];
    for (int i = 1;i<[comps weekday];i++){
        [_dayArray2 insertObject:@"" atIndex:0];
    }
    
    _dayArray = _dayArray1;
    [dayCollectionView reloadData];

}

-(void)setBusyTimeArray:(NSMutableArray *)busyTimeArray
{
    if (_busyTimeArray){
        _busyTimeArray = nil;
    }
    _busyTimeArray = [[NSMutableArray alloc] initWithArray:busyTimeArray];
    
}

//判断一个月有多少天
-(int)countOfDayInYear:(int)year month:(int)month
{
    int day=0;
    switch(month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day=31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day=30;
            break;
        case 2:
            if( (year%4==0 &&(year%100)!=0)||year%400==0)
                day = 28;
            else
                day =29;
            break;
        default :
            break;
    }
    return day;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
